<template>
  <div class="about">
    <div class="car-list-content">
      <ul class="car-list-item" v-for="item in list" :key="item.id">
        <li>
          <img :src="item.img" alt="" />
        </li>
        <li>
          <h2>{{ item.title }}</h2>
          <span>里程：{{ item.mileage }}</span>
          |
          <span>车价：{{ item.price }}</span>
          |
          <span>距离远近：{{ item.distance }}</span>
        </li>
      </ul>
    </div>
    <div class="loading" ref="loading">{{ tip }}</div>
  </div>
</template>
<script>
/**
 * count: 0
desc: "便基反做基教成证带心去无常得王组度越军矿光属打满况林矿结太观"
distance: 40
id: "320000198405297246"
img: "http://dummyimage.com/150x150/f2e679, 保定市)"
mileage: 4
price: 29
title: "宝马三系_少温机除"
type: 1
 */

// 模拟接口慢的情况
import { debounce } from 'lodash'
export default {
  data() {
    return {
      opt: {
        page: 0,
        size: 10,
      },
      tip: 'loading...',
      list: [],
      // 1. 定义
      handleFetchData: null,
    }
  },
  created() {
    this.getData()
  },
  mounted() {
    this.handleFetchData = debounce(this.getData, 1000)
    // loading 元素，监听这个loading元素，如果这个loading元素看到了，就说明滚动到了最下方。然后就请求分页数据，
    // 渲染后10条数据
    const io = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        console.log(entries[0].isIntersecting, 'entries----------')
        if (this.handleFetchData) {
          this.handleFetchData()
        }
      }
    })
    // start observing
    io.observe(this.$refs.loading)
  },
  methods: {
    sleep(time = 500) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(true)
        }, time)
      })
    },
    async getData() {
      // 每次调用让接口延迟几秒执行
      // await this.sleep()
      this.opt.page++
      console.log('opt------page:', this.opt.page)
      // opt._page如果到了10就说明数据请求结束了，没有数据了
      // 不能全等，一个条件，
      if (this.opt.page >= 11) {
        console.log('--------------tip')
        this.tip = '我已经到底部了'
        return
      }
      const data = await this.$http.get('/api/car', { params: this.opt })
      console.log('data:', data)
      this.list = [...this.list, ...data.data.list]
      console.log('data:----------list', this.list)
    },
  },
}
</script>
<style lang="scss" scoped>
.about {
  height: 100%;
}
.loading {
  height: 0.8rem;
  text-align: center;
  line-height: 0.8rem;
  font-size: 30px;
  background: lightcoral;
  color: #fff;
}
</style>
